package com.business.file.controller;

import com.business.common.utils.FileUtil;
import com.business.file.rabbitMq.RabbitMqSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping(value = "/images")
public class ImagesController {

    @Value("${file.base-path}")
    private String basePath;

    @Autowired
    private RabbitMqSender rabbitMqSender;

    private Logger logger = LoggerFactory.getLogger(ImagesController.class);


    @GetMapping("/**")
    public void getImage(@RequestParam(value = "original", required = false) boolean original, HttpServletRequest request, HttpServletResponse response) {
        String url = request.getRequestURI();
        String path = url.replaceAll("/file", "");
        String fullFilePath = null;
        if (original) {//原图
            fullFilePath = basePath + path;
        } else {//压缩图的路径
            String uploadResizedPath = path.replaceAll("/images/", "/images-resized/");
            fullFilePath = basePath + uploadResizedPath;
        }
        File file = new File(fullFilePath);
        if (!file.exists() || file.isDirectory()) {
            if (original) {
                logger.error("文件路径错误,url:" + url);
                response.setStatus(404);
                return;
            } else {//如果压缩图片不存在则用原图
                fullFilePath = basePath + path;
                file = new File(fullFilePath);
                if (file.length() > 81920) {
                    //发送消息 压缩图片
                    rabbitMqSender.resizedImage(fullFilePath);
                }
            }
        }
        try {
            ServletOutputStream out = response.getOutputStream();
            FileUtil.outByOutputStream(out, file);
        } catch (IOException e) {
            response.setStatus(404);
            logger.error(e.getMessage(), e);
        }
    }


}
